﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Collections;

using ComLib.Entities;
using ComLib.Authentication;
using ComLib.Mvc.Models;


namespace ComLib.Mvc.Lib
{
    public class PagerHelper
    {
        /// <summary>
        /// Build pager view model from a non-paged list of items.
        /// </summary>
        /// <param name="posts"></param>
        /// <returns></returns>
        public static EntityListViewModel<T> ConvertToListViewModel<T>(IList<T> items, string modelName, IDictionary conf) where T : IEntity
        {
            if (string.IsNullOrEmpty(modelName))
                modelName = typeof(T).Name;

            // Url for pager.
            // This List page uses a paged result by default.
            // Since we are getting ALL the posts with matching tags, just wrap them in a paged result.
            string url = string.Format("/{0}/index/{1}", modelName, 1);

            // Check for empty.
            if (items == null)
            {
                var result = new EntityListViewModel<T>(PagedList<T>.Empty, url, false);
                result.ControlPath = "ModelList";
            }

            PagedList<T> pagedList = new PagedList<T>(1, items.Count + 1, items.Count, items);
            var viewModel = new EntityListViewModel<T>(pagedList, url, false);
            BuildViewModel<T>(viewModel, default(T), "ModelList", false, conf);
            viewModel.Items = pagedList;
            viewModel.PageIndex = pagedList.PageIndex;
            viewModel.TotalPages = pagedList.TotalPages;
            viewModel.ShowEditDelete = false;
            return viewModel;
        }


        public static void BuildViewModel<T>(EntityBaseViewModel view, T entity, string controlPath, bool useForm, IDictionary conf) where T: IEntity
        {
            var modelname = typeof(T).Name;
            var editUrl = "/" + modelname + "/edit/";
            var deleteUrl = "/" + modelname + "/delete/";
            var indexUrl = "/" + modelname + "/index/";
            bool allowEdit = false;

            if (entity != null)
            {
                editUrl += entity.Id;
                deleteUrl += entity.Id;
                allowEdit = Auth.IsUserOrAdmin(entity.CreateUser);
            }
            view.Name = modelname;
            view.UrlEdit = editUrl;
            view.UrlDelete = deleteUrl;
            view.UrlIndex = indexUrl;
            view.AllowDelete = allowEdit;
            view.AllowDelete = allowEdit;
            view.ControlPath = controlPath;
            view.Config = conf;
            if (view is EntityDetailsViewModel)
                ((EntityDetailsViewModel)view).Entity = entity;
            else if (view is EntityFormViewModel)
                ((EntityFormViewModel)view).Entity = entity;
        }
    }
}
